package com.ag.lzw.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.ag.bean.TbFeedbackAnnex;
import com.ag.bean.TbTask;
import com.ag.bean.TbTaskFeedback;
import com.ag.common.PageUtil;
import com.ag.lwc.service.impl.LogService;
import com.ag.lzw.common.DateHandeler;
import com.ag.lzw.dao.LzwTaskDAO;
import com.ag.lzw.dao.LzwTbFeedbackAnnexDAO;
import com.ag.lzw.dao.LzwTbTaskFeedbackDAO;
import com.ag.lzw.service.TaskTrackHandel;
import com.ag.lzw.vo.FeedBackVo;
import com.ag.lzw.vo.TaskAnnexVo;
import com.ag.lzw.vo.TrackVo;

@Service("TaskTrackHandelImpl")
public class TaskTrackHandelImpl implements TaskTrackHandel {


	@Resource(name = "lzwTaskDao")
	private LzwTaskDAO taskDAO;
	@Resource(name = "lzwTbTaskFeedbackDAO")
	private LzwTbTaskFeedbackDAO taskFeedBackDAO;
	@Resource(name = "lzwTbFeedbackAnnexDAO")
	private LzwTbFeedbackAnnexDAO feedbackAnnexDAO;
	@Resource(name="LogService")
	private LogService logService;


	private static final Logger logger = Logger.getLogger(TaskTrackHandelImpl.class);
	
	@Override
	public boolean saveFeedBack(FeedBackVo back) {

		TbTaskFeedback feedback = new TbTaskFeedback();
		
		feedback.setTfId(back.getTfId());
		logger.info("Feedback id:"+back.getTfId());
		//初始化审批状态
		feedback.setTfCheck("0");
		feedback.setTfTime(new Date());
		feedback.setTfText(back.getTfText());
		feedback.setTfPeople(back.getTfPeople());
        /**
         * 如果有备注信息，记录入数据表的B字段
         */
		if(back.getTfNote()!=null){
			feedback.setB(back.getTfNote());
		}
		
		TbTask t = this.taskDAO.findATaskById(back.getTid());
		if (t != null) {
			feedback.setTbTask(t);
			logger.info(" taskid of FeedBack ：" + t.getTId());
		} else {
			logger.info("Save FeedBack faile!Because of No Task loaded!");
			return false;
		}

		this.taskFeedBackDAO.save(feedback);

		//记录日志
		logger.info("logger start!");
		TbTask tt = this.taskDAO.findTaskDetailById(back.getTid());
		if(tt!=null){
			logService.saveByUser(back.getTfText(), tt.getTbEvent().getEId(), this.logService.LOG_TASK_FEEDBACK, back.getTfPeople());
		} else {
			logService.saveByUser(back.getTfText(), back.getTid(), this.logService.LOG_TASK_FEEDBACK, back.getTfPeople());
		}
		logger.info("log over!");

		if(back.getTfAnnexId().length()>0 && !(back.getTfAnnexId().equals(""))){
			String[] annexs = back.getTfAnnex().split(",");
			String[] annexids = back.getTfAnnexId().split(",");
			logger.info("the number of annex:" + annexs.length);
			for (int i = 0; i < annexs.length; i++) { // 遍历反馈上传的附件，批量处理
				String annexid = annexids[i].substring(0, annexids[i].indexOf(".")); // 分离出附件的ID
				TbFeedbackAnnex tfa = feedbackAnnexDAO.findById(annexid); // 获取已上传附件的信息
				// 更新附件信息
				tfa.setTaName(annexs[i]);
				logger.info("finding feedback for annex!");
				TbTaskFeedback ttf = new TbTaskFeedback();//taskFeedBackDAO.findById(feedback.getTfId());//
				//关联反馈记录与反馈附件
				ttf.setTfId(feedback.getTfId());
				tfa.setTbTaskFeedback(ttf);
				tfa.setTcId(back.getTid());
				//使用B字段记录文件在服务器上的全文件名
                tfa.setB(annexids[i]);
				feedbackAnnexDAO.attachDirty(tfa);
				logger.info("Updated the feedback annex id:" + tfa.getTaId());
			}
		}

		logger.info("Save FeedBack Succ!");
		return true;
	}
	
	@Override
	public PageUtil getTrackListByPage(Map<String, String> queryOption) {
		int firstRow = 0;
		int maxRow = 5;
		int page = 0;
		int total = 0;
		String tid = null;
		List<TbTaskFeedback> list = null;
		if (queryOption.containsKey("tid") && !queryOption.get("tid").isEmpty()) {
			tid = queryOption.get("tid");
			logger.info("queryTrack by tid:" + tid);
		} else {
			logger.info("No id in queryOption!");
			return null;
		}

		String hql = "From TbTaskFeedback as ttf "
				+ "left join fetch ttf.tbTask as tt " 
				+ "where tt.TId = '" + tid + "'"
				+ "order by ttf.tfCheck " 
				+ ",ttf.tfTime desc";

		if (queryOption.containsKey("page") && !queryOption.get("page").isEmpty()) {
			page = Integer.parseInt(queryOption.get("page"));
			logger.info("query track list at page:" + page);
			firstRow = maxRow * (page - 1);
			list = this.taskDAO.findByPage(hql, firstRow, maxRow);

		} else {
			logger.info("No Page in queryOption!");
			return null;
		}

		if (list.size() == 0) {
			logger.info("No Track found! -- length:" + list.size());
			return null;
		} else {
			logger.info("thr length of result list is :" + list.size());
			List<FeedBackVo> tracklist = new ArrayList<FeedBackVo>();

			for (TbTaskFeedback ttf : list) {
				FeedBackVo fbv = new FeedBackVo();
				fbv.setFbid(ttf.getTfId());
				fbv.setTid(ttf.getTbTask().getTId());
				fbv.setTfTime(DateHandeler.DateToString(ttf.getTfTime()));
				fbv.setTfText(ttf.getTfText());
				fbv.setTfPeople(ttf.getTfPeople());
				fbv.setTfCheck(ttf.getTfCheck());

/*				logger.info("finding annex by feedback id" + fbv.getFbid());
				// 根据反馈的ID查找其属下的附件
				List<TbFeedbackAnnex> fbaList = feedbackAnnexDAO.findByFeedbackId(fbv.getFbid());
				List<TaskAnnexVo> annexs = new ArrayList<TaskAnnexVo>();
				// 遍历查询的结果，用VO封装附件信息
				for (TbFeedbackAnnex tfa : fbaList) {
					TaskAnnexVo tav = new TaskAnnexVo();
					tav.setFilename(tfa.getTaName());
					tav.setFileid(tfa.getTaAddress());
					annexs.add(tav);
				}
				logger.info("Feedback annex length:" + fbaList.size());
				fbv.setAnnex(annexs);*/

				tracklist.add(fbv);
			}
			total = taskFeedBackDAO.getCountofTrack(tid);
			logger.info("the summary of trackList is:" + total);
			PageUtil pageUitl = new PageUtil();
			pageUitl.setMaxRow(maxRow);
			pageUitl.setPage(page);
			pageUitl.setTotal(total);
			pageUitl.setList(tracklist);
			return pageUitl;
		}
	}

	/**
	 * 获取任务反馈信息的方法
	 * 
	 * @param id
	 *            String 任务号id
	 * @return trackList TrackVo 属于一个任务的所有反馈信息
	 */
	@Override
	public List<TrackVo> getTrackListByTask(String id) {

		logger.info("\n ------ TrackTask ID:" + id);
		List list = taskFeedBackDAO.findByTaskId(id);
		Iterator it = list.iterator();
		if (it.hasNext()) {
			List<TrackVo> trackList = new ArrayList<TrackVo>();
			while (it.hasNext()) {
				TbTaskFeedback feedback = (TbTaskFeedback) it.next();

				TrackVo trackvo = new TrackVo();
				trackvo.setCheck(feedback.getTfCheck());
				trackvo.setId(id);
				trackvo.setPeople(feedback.getTfPeople());
				trackvo.setText(feedback.getTfText());
				trackvo
						.setTime(DateHandeler
								.DateToString(feedback.getTfTime()));

				trackList.add(trackvo);
			}
			return trackList;
		}
		return null;
	}
	
	/**
	 * 查询属于任务的新任务反馈
	 * @param tid
	 * @return
	 */
	@Override
	public int getNewFeedbackSummary(String tid){
		List list = taskFeedBackDAO.findNewByTaskId(tid);
		return list.size();
	}
}
